package com.loyal.camerax.view

import android.content.Context
import android.view.View
import androidx.annotation.AttrRes
import androidx.annotation.StyleRes
import androidx.appcompat.widget.PopupMenu
import com.loyal.camerax.R
import com.loyal.camerax.annotation.TorchFlashState

class TorchFlashMenu : PopupMenu {
    private var listener: OnTorchFlashChangedListener? = null

    constructor(context: Context, anchor: View) : super(context, anchor) {
        initMenu()
    }

    constructor(context: Context, anchor: View, gravity: Int) : super(context, anchor, gravity) {
        initMenu()
    }

    constructor(
        context: Context,
        anchor: View,
        gravity: Int,
        @AttrRes popupStyleAttr: Int,
        @StyleRes popupStyleRes: Int
    ) : super(context, anchor, gravity, popupStyleAttr, popupStyleRes) {
        initMenu()
    }

    fun setOnTorchFlashChangedListener(listener: OnTorchFlashChangedListener?) {
        this.listener = listener
    }

    private fun initMenu() {
        inflate(R.menu.menu_flash)

        //强制显示菜单图标
        setForceShowIcon(true)
        //使用反射，
        /*try {
            val field = javaClass.getDeclaredField("mPopup")
            field.isAccessible = true
            val mHelper = field.get(this) as? MenuPopupHelper?
            mHelper?.setForceShowIcon(true)
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        }*/
        setOnMenuItemClickListener { menuItem ->
            when (menuItem.itemId) {
                R.id.menu_flash_off -> listener?.onTouchFlashChanged(TorchFlashState.OFF) ?: false
                R.id.menu_flash_on -> listener?.onTouchFlashChanged(TorchFlashState.ON) ?: false
                R.id.menu_flash_auto -> listener?.onTouchFlashChanged(TorchFlashState.AUTO) ?: false
                R.id.menu_flash_torch -> listener?.onTouchFlashChanged(TorchFlashState.TORCH)
                    ?: false

                else -> false
            }
        }
    }

    interface OnTorchFlashChangedListener {
        fun onTouchFlashChanged(@TorchFlashState state: String): Boolean
    }
}
